import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import metar.CloudsMetar;
import metar.ObservationDateMetar;
import metar.WindMetar;
import model.CityModel;
import model.CountryModel;
import model.WeatherModel;
import controller.Actions;
import controller.Controller;

import view.ViewInterface;

/**
 * einfache TestGui für unsere Wetterstation
 * @author Michel Metzger, Java-Kurs 2013
 * @version 1.0.0
 *
 */
@SuppressWarnings("rawtypes")
public class TestGui implements Observer, ViewInterface {

	private Controller controller;
	
	private JFrame frame = null;
	
	private JComboBox comboCountry = null;
	private JComboBox comboCity = null;
	private JTextArea textArea = null;
	
	private ArrayList<CountryModel> countryList = null;
	private ArrayList<CityModel> cityList = null;
	
	private String city = "";
	private boolean ignoreItemEvents= false;	// Während dem Aufbau der ComboBox werden die ItemEvents nicht ausgewertet
	
	public TestGui(Controller control) {
		super();
		this.controller = control;
		build();
	}

	@Override
	public void setController(Controller control) {
		this.controller = control;
	}

	@Override
	public void build() {
		
		/**
		 * Fenster aufbauen
		 */
		frame = new JFrame();
		frame.setTitle("TestGui      by Michael Metzger 2013");
		frame.setPreferredSize(new Dimension(500, 400));
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));

		JPanel panel1 = new JPanel();
		panel1.setLayout(new FlowLayout());
		panel1.setBackground(new Color(153, 204, 204));

		JLabel labelCountry = new JLabel("Country: ");
		panel1.add(labelCountry);
		
		comboCountry = new JComboBox();
		comboCountry.setPreferredSize(new Dimension(200, 20));
		comboCountry.setMaximumSize(new Dimension(300, 200));
		comboCountry.setEditable(false);
		comboCountry.addItemListener(new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent ev) {
				if (ignoreItemEvents) {
					return;
				}
				if (ev.getStateChange() == ItemEvent.SELECTED) {
					city = "";
					textArea.setText("");
					String item = (String)comboCountry.getSelectedItem();
					if (item != null) {
						for (int i = 0; i < countryList.size(); ++i) {
							if (item.compareTo(countryList.get(i).toString()) == 0) {
								controller.setItemArgument(countryList.get(i));
								controller.actionPerformed(Actions.GET_CITIES);
								break;
							}
						}
					}
				}
			}
		});
		panel1.add(comboCountry);

		frame.add(panel1);

		JPanel panel2 = new JPanel();
		panel2.setLayout(new FlowLayout());
		panel2.setBackground(new Color(153, 204, 204));

		JLabel labelCity = new JLabel("City: ");
		panel2.add(labelCity);
		
		comboCity = new JComboBox();
		comboCity.setPreferredSize(new Dimension(200, 20));
		comboCity.setMaximumSize(new Dimension(300, 200));
		comboCity.setEditable(false);
		comboCity.addItemListener(new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent ev) {
				if (ignoreItemEvents) {
					return;
				}
				if (ev.getStateChange() == ItemEvent.SELECTED) {
					city = "";
					textArea.setText("");
					String item = (String)comboCity.getSelectedItem();
					if (item != null) {
						for (int i = 0; i < cityList.size(); ++i) {
							if (item.compareTo(cityList.get(i).toString()) == 0) {
								city = cityList.get(i).getName();
								System.out.println("city=" + city);
								controller.setItemArgument(cityList.get(i));
								controller.actionPerformed(Actions.GET_WEATHER);
								break;
							}
						}
					}
				}
			}
		});
		panel2.add(comboCity);

		frame.add(panel2);

		textArea = new JTextArea();
		textArea.setBackground(new Color(255, 255, 102));
		textArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
		textArea.setEditable(false);

		JScrollPane scrollPane = new JScrollPane(textArea);
		scrollPane.setPreferredSize(new Dimension(650, 500));
		scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);		
//		scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);		
		frame.add(scrollPane);
		
		JPanel panel3 = new JPanel();
		panel3.setLayout(new FlowLayout());
		panel3.setBackground(new Color(153, 204, 204));
		
		JButton exitButton = new JButton(" Exit ");
		exitButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				System.exit(0);
			}
		});
		panel3.add(exitButton);
		frame.add(panel3);
		
		frame.pack();

		/**
		 * Fenster zentieren
		 */
		Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
	    frame.setLocation((int) ((d.getWidth() - frame.getWidth()) / 2), (int) ((d.getHeight() - frame.getHeight()) / 2));
		
		frame.setVisible(true);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable o, Object arg) {
		try {
			if (arg instanceof ArrayList<?> && ((ArrayList) arg).size() > 0) {
				/**
				 * Countries in die ComboBox übernehmen
				 */
				if (((ArrayList<CountryModel>)arg).get(0) instanceof CountryModel) {
					countryList = (ArrayList<CountryModel>)arg;
					ignoreItemEvents = true;
					comboCountry.setEnabled(false);
					comboCountry.removeAllItems();
					for (int i = 0; i < countryList.size(); ++i) {
						comboCountry.addItem(countryList.get(i).toString());
					}
					comboCountry.setEnabled(true);
					comboCountry.repaint();
					ignoreItemEvents = false;
					
				} else if (((ArrayList<CityModel>)arg).get(0) instanceof CityModel) {
					/**
					 * Orte in die ComboBox übernehmen
					 */
					cityList = (ArrayList<CityModel>)arg;
					ignoreItemEvents = true;
					comboCity.setEnabled(false);
					comboCity.removeAllItems();
					for (int i = 0; i < cityList.size(); ++i) {
						comboCity.addItem(cityList.get(i).toString());
					}
					comboCity.setEnabled(true);
					comboCity.repaint();
					ignoreItemEvents = false;
			
				} else if (((ArrayList<WeatherModel>)arg).get(0) instanceof WeatherModel) {
					/**
					 * Wetterdaten in der textArea anzeigen
					 */
					WeatherModel wm = ((ArrayList<WeatherModel>)arg).get(0);
					
					if (wm != null) {
						ObservationDateMetar oDate = new ObservationDateMetar();
						if (wm.getObservationTime() != null && !wm.getObservationTime().isEmpty()) {
							oDate.parseParam(wm.getObservationTime());
						}
						String windInfo = ""; 
						WindMetar wind = new WindMetar();
						if (wm.getWindDirectionInfo() != null && !wm.getWindDirectionInfo().isEmpty()) {
							wind.parseParam(wm.getWindDirectionInfo());
							windInfo = " ==> " + WindMetar.windDirectionAsString(wind.getDirection());
							if (wind.getSpeed() > 0) {
								windInfo += " , " + wind.getSpeed() + "kt"; 
							}
						}
						String cloudInfo = "";
						CloudsMetar clouds = new CloudsMetar();
						if (wm.getCloudiness() != null && !wm.getCloudiness().isEmpty()) {
							clouds.parseParam(wm.getCloudiness());
							cloudInfo = " ==> " + clouds.getClouds();
							if (clouds.getCloudCeiling() > 0) {
								cloudInfo += " " + clouds.getCloudCeiling() + "ft";
							}
						}
						textArea.setText("City=               " + city + "\n\n");
						textArea.append("info=               " + wm.getInfo() + "\n");
						textArea.append("observationTime=    " + wm.getObservationTime() + " ==> " + oDate.getDate() + "\n");
						textArea.append("timestamp=          " + wm.getTimeStamp() + "\n");
						textArea.append("date=               " + wm.getDate() + "\n");
						textArea.append("temperature=        " + wm.getTemperature() + "°C\n");
						textArea.append("airPressure=        " + wm.getAirPressure() + "hPa\n");
						textArea.append("windDirectionInfo=  " + wm.getWindDirectionInfo() + windInfo + "\n");
						textArea.append("cloudiness=         " + wm.getCloudiness() + cloudInfo + "\n");
						textArea.append("visibility=         " + wm.getVisibility() + "m\n");
					}
					
					
				}
			}
		} catch (Exception e) {
//			JOptionPane.showMessageDialog(null, "Unknown data!", "Error", JOptionPane.ERROR_MESSAGE);
		}
	}

}
